package com.zzyl.framework.interceptor;


import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class MemberInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取header中的token
        String token = request.getHeader("authorization");

        //2.判断token是否存在
        if (StringUtils.isEmpty(token)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        //3.如果token存在，解析token
        Claims claims = tokenService.parseToken(token);


        //4.如果token存在，响应401
        if (ObjectUtils.isEmpty(claims)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        //5.如果token解析成功，获取token中的数据
        //TODD
        //Long userId = Long.valueOf(String.valueOf(claims.get("userId")));
        Long userId = MapUtil.getLong(claims,"userId");

        //6.判断数据是否为空，如果为空，则响应401
        if(ObjectUtils.isEmpty(userId)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        //7.如果数据不为空，将数据存入ThreadLocal中
        UserThreadLocal.set(userId);

        //8.成功
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            UserThreadLocal.remove();
    }
}
